<template>
  <div id="function">
    <div class="max-width">
      <!-- 空投 -->
      <div id="join">
        <!-- 复制推广链接 -->
        <div v-if="$store.state.isRegister">
          <h1 class="title">{{ $t(`intro.function.join.标题2`) }}</h1>

          <div class="detail-box flex flex-cc">
            <el-input class="mr-5" readonly v-model="inviteLink"></el-input>
            <el-button type="primary" @click="copyLink(inviteLink)">
              {{ $t(`intro.function.join.复制推广链接`) }}
            </el-button>
          </div>
        </div>

        <!-- 领取空投 -->
        <div v-else>
          <h1 class="title">{{ $t(`intro.function.join.标题1`) }}</h1>

          <div class="detail-box flex flex-cc">
            <el-input
              class="mr-5"
              readonly
              :placeholder="$t(`intro.function.join.输入`)"
              v-model="userAddress"
            >
            </el-input>
            <el-button type="primary" @click="register">
              {{ $t(`common.领取`) }}
            </el-button>
          </div>
        </div>
      </div>

      <!-- 推荐奖 -->
      <div>
        <h1 class="title">{{ $t(`intro.function.rec.标题`) }}</h1>

        <div class="detail-box">
          <!-- <div class="fz-18 fw-bold">
            {{ $t(`common.待释放`) }}：
            {{ $store.state.user.recommendUsdt || 0 }}USDT +
            {{ $store.state.user.recommendCurrency || 0 }}
            {{ $t(`common.代币`) }}
          </div> -->

          <div class="fz-18 fw-bold">
            {{ $t(`common.待释放`) }}：
            {{ $store.state.user.recommendUsdtPrizePoolBalance || 0 }}USDT +
            {{ $store.state.user.recommendCurrencyPrizePoolBalance || 0 }}
            {{ $t(`common.代币`) }}
          </div>

          <!-- 倒计时 -->
          <div class="fz-24" v-if="$store.state.config.endTime">
            <count-down
              :format="`DD ${$t('common.天')} HH ${$t('common.时')} mm ${$t(
                'common.分'
              )} ss ${$t('common.秒')}`"
              :millisecond="false"
              :time="
                new Date(
                  $store.state.config.endTime.replace(/-/g, '/')
                ).getTime() - new Date().getTime()
              "
              @finish="$store.commit('setIsFinish', 1)"
            ></count-down>
          </div>

          <!-- <div class="fz-18 cl-primary">
            （{{ $t(`intro.function.rec.剩余数量`) }}：
            {{ $store.state.user.recommendUsdtPrizePoolBalance || 0 }}USDT +
            {{ $store.state.user.recommendCurrencyPrizePoolBalance || 0 }}
            {{ $t(`common.代币`) }} ）
          </div> -->

          <div class="cl-basic">
            {{ $t(`intro.function.rec.介绍1`) }}
            {{ $store.state.config.recommendUsdt || 0 }}USDT +
            {{ $store.state.config.recommendCurrency || 0 }}
            {{ $t(`common.代币`) }}
          </div>
        </div>
      </div>

      <!-- 团队奖 -->
      <div>
        <h1 class="title">{{ $t(`intro.function.team.标题`) }}</h1>

        <div class="detail-box">
          <div class="fz-18 fw-bold">
            {{ $t(`common.待释放`) }}：
            {{
              $store.state.user.teamAwardCurrency ||
              $store.state.config.teamAwardCurrency ||
              0
            }}
            {{ $t(`common.代币`) }}
          </div>
          <div class="cl-basic">
            {{ $t(`intro.function.team.介绍1`) }}
            {{ $store.state.config.teamAwardPopularizeNum || 0 }}
            {{ $t(`intro.function.team.介绍2`) }}：
            {{ $store.state.config.teamAwardCurrency || 0 }}
            {{ $t(`common.代币`) }}
          </div>
        </div>
      </div>

      <!-- 私募奖 -->
      <div
        v-if="
          $store.state.config.directExchangeCashBackUsdtProp ||
          $store.state.config.directExchangeCashBackProp
        "
      >
        <h1 class="title">{{ $t(`intro.function.exchange.标题`) }}</h1>

        <div class="detail-box">
          <div class="fz-18 fw-bold">
            {{ $t(`common.奖励`) }}：
            <span v-if="$store.state.config.directExchangeCashBackUsdtProp">
              {{ $store.state.user.exchangeCashBackUsdt || 0 }}
              USDT
            </span>
            <span
              v-if="
                $store.state.config.directExchangeCashBackUsdtProp &&
                $store.state.config.directExchangeCashBackProp
              "
            >
              +
            </span>
            <span v-if="$store.state.config.directExchangeCashBackProp">
              {{ $store.state.user.exchangeCashBackCurrency || 0 }}
              {{ $t(`common.代币`) }}
            </span>
          </div>
          <div
            class="cl-basic mt-10"
            style="line-height: 1.5"
            v-if="$store.state.config.directExchangeCashBackUsdtProp"
          >
            {{ $t(`intro.function.exchange.私募`) }}，
            {{ $t(`intro.function.exchange.直推`) }}
            {{
              $store.state.config.directExchangeCashBackUsdtProp * 100 || 0
            }}%，
            {{ $t(`intro.function.exchange.二代`) }}
            {{
              $store.state.config.indirectExchangeCashBackUsdtProp * 100 || 0
            }}%，
            {{ $t(`intro.function.exchange.三代`) }}
            {{
              $store.state.config.threeExchangeCashBackUsdtProp * 100 || 0
            }}%，
            {{ $t(`intro.function.exchange.四代`) }}
            {{ $store.state.config.fourExchangeCashBackUsdtProp * 100 || 0 }}%，
            {{ $t(`intro.function.exchange.五代`) }}
            {{ $store.state.config.fiveExchangeCashBackUsdtProp * 100 || 0 }}%，
            {{ $t(`intro.function.exchange.六代`) }}
            {{ $store.state.config.sixExchangeCashBackUsdtProp * 100 || 0 }}%；
            {{ $t(`common.奖励`) }} USDT
          </div>
          <div
            class="cl-basic mt-10"
            style="line-height: 1.5"
            v-if="$store.state.config.directExchangeCashBackProp"
          >
            {{ $t(`intro.function.exchange.私募`) }}，
            {{ $t(`intro.function.exchange.直推`) }}
            {{ $store.state.config.directExchangeCashBackProp * 100 || 0 }}%，
            {{ $t(`intro.function.exchange.二代`) }}
            {{ $store.state.config.indirectExchangeCashBackProp * 100 || 0 }}%，
            {{ $t(`intro.function.exchange.三代`) }}
            {{ $store.state.config.threeExchangeCashBackProp * 100 || 0 }}%，
            {{ $t(`intro.function.exchange.四代`) }}
            {{ $store.state.config.fourExchangeCashBackProp * 100 || 0 }}%，
            {{ $t(`intro.function.exchange.五代`) }}
            {{ $store.state.config.fiveExchangeCashBackProp * 100 || 0 }}%，
            {{ $t(`intro.function.exchange.六代`) }}
            {{ $store.state.config.sixExchangeCashBackProp * 100 || 0 }}%；
            {{ $t(`common.奖励`) }} {{ $t(`common.代币`) }}
          </div>
        </div>
      </div>

      <!-- 明细 -->
      <div class="detail-box ta-center mt-30">
        <div class="flex flex-cc flex-rb">
          <div class="fz-16">
            <div class="fw-bold">
              {{ $t(`intro.function.detail.可提金额`) }}
            </div>
            <div class="cl-primary">
              {{ $store.state.user.usdt || 0 }}USDT +
              {{ $store.state.user.currency || 0 }}
              {{ $t(`common.代币`) }}
            </div>
          </div>

          <div class="flex fz-16">
            <div class="mr-10">
              <div class="fw-bold">
                {{ $t(`intro.function.detail.直推人数`) }}
              </div>
              <div class="cl-primary">
                {{ $store.state.user.directRecommendNum || 0 }}
              </div>
            </div>

            <div>
              <div class="fw-bold">
                {{ $t(`intro.function.detail.伞下人数`) }}
              </div>
              <div class="cl-primary">
                {{ $store.state.user.popularizeNum || 0 }}
              </div>
            </div>
          </div>
        </div>

        <div class="mt-20">
          <el-button type="primary" :disabled="isLocked" @click="release">
            {{ isLocked ? $t(`common.正在提现中`) : $t(`common.领取`) }}
          </el-button>

          <div class="cl-basic mt-10">
            （{{ $t(`intro.function.detail.点击领取`) }} USDT +
            {{ $t(`common.代币`) }}）
          </div>
        </div>
      </div>

      <!-- IDO -->
      <div>
        <h1 class="title">{{ $t(`intro.function.ido.标题`) }}</h1>

        <div class="detail-box">
          <div class="flex flex-cc">
            <el-input
              class="mr-5"
              type="number"
              :min="10"
              :max="300"
              :placeholder="$t(`intro.function.ido.输入`)"
              v-model="usdtAmount"
            >
            </el-input>
            <el-button type="primary" @click="presale">
              {{ $t(`common.提交`) }}
            </el-button>
          </div>

          <div class="ta-left mt-20">
            <div>
              {{ $t(`intro.function.ido.介绍1`) }}：1USDT =
              {{ $store.state.config.currencyExchangeRate || 0 }}
              {{ $t(`common.代币`) }}；
            </div>
            <div>{{ $t(`intro.function.ido.介绍2`) }}；</div>
            <div>{{ $t(`intro.function.ido.介绍3`) }}。</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import baseFunction from '@/components/base_function.vue'
import web3 from '@/assets/js/web3'
import { Message } from 'element-ui'
import { CountDown } from 'vant'
import { getUrlParams } from '@/assets/js/utils'
import { BigNumber } from 'bignumber.js'

export default {
  data() {
    return {
      inviterAddress: '', // 邀请者地址
      userAddress: '', // 用户输入的钱包地址
      inviteLink: '', // 用户的推广链接
      usdtAmount: '', // 用户输入的兑换USDT余额
      isLocked: false, // 是否锁住提现按钮
    }
  },

  mounted() {
    this.getLockStatus()
    this.inviterAddress =
      getUrlParams().inviterAddress || process.env.VUE_APP_IS_TEST
        ? '0x0000000000000000000000000000000000000000'
        : ''
    // console.log(this.toBigNumber(4.1))
  },

  methods: {
    /**
     * 注册
     */
    register() {
      if (this.$store.state.isFinish) {
        return Message.warning(this.$t(`common.活动时间已结束`))
      }

      if (!this.userAddress) {
        return Message.warning(this.$t(`common.请先解锁钱包插件`))
      }

      if (!this.inviterAddress && !process.env.VUE_APP_IS_TEST) {
        return Message.warning(this.$t(`common.请从邀请链接进入此应用`))
      }

      web3.initContract('USDT').then(() => {
        web3.approve().then(() => {
          web3.initContract('IDO').then(() => {
            web3.checkIsRegister(this.userAddress).then(async (flag) => {
              if (!flag) {
                web3.register(this.inviterAddress).then((hash) => {
                  web3.checkIsRegister(this.userAddress).then(async (flag) => {
                    if (flag) {
                      const res = await this.submitRegister(hash)

                      if (res) {
                        Message.success(this.$t('common.领取成功'))
                      }
                    } else {
                      Message.error(this.$t('common.领取失败'))
                    }
                  })
                })
              }
            })
          })
        })
      })
    },

    /**
     * 释放
     */
    async release() {
      const { usdt, currency } = this.$store.state.user

      if (this.$store.state.isFinish) {
        return Message.warning(this.$t(`common.活动时间已结束`))
      }

      if (!this.userAddress) {
        return Message.warning(this.$t(`common.请先解锁钱包插件`))
      }

      if (!usdt && !currency) {
        return Message.warning(this.$t(`common.USDT或代币约不足`))
      }

      web3.initContract('IDO').then(() => {
        web3.checkIsRegister(this.userAddress).then((flag) => {
          this.$store.commit('setIsRegister', flag)

          if (flag) {
            web3.initContract('USDT').then(() => {
              web3.approve().then(() => {
                web3.initContract('IDO').then(async () => {
                  const usdtAmount = this.toBigNumber(usdt)
                  const tokenAmount = this.toBigNumber(currency, 18)
                  const nonce = await web3.getNonce()

                  const params = {
                    walletAddress: this.userAddress,
                    usdtAmount,
                    tokenAmount,
                    nonce: Number(nonce) + 1,
                  }

                  const { code, data: sign } = await this.$apis.getReleaseSign(
                    params
                  )

                  if (code === 200) {
                    web3
                      .release(usdtAmount, tokenAmount, sign)
                      .then(async (hash) => {
                        const params = {
                          walletAddress: this.userAddress,
                          usdt,
                          currency,
                          hashValue: hash,
                        }

                        const { code } = await this.$apis.saveReleaseInfo(
                          params
                        )

                        if (code === 200) {
                          this.isLocked = true
                          this.getLockStatus()
                          Message.success(this.$t('common.交易已上链'))
                        }
                      })
                  }
                })
              })
            })
          } else {
            Message.error(`common.请先领取空投`)
          }
        })
      })
    },

    /**
     * 私募
     */
    async presale() {
      if (this.$store.state.isFinish) {
        return Message.warning(this.$t(`common.活动时间已结束`))
      }

      if (!this.userAddress) {
        return Message.warning(this.$t(`common.请先解锁钱包插件`))
      }

      if (!this.usdtAmount) {
        return Message.warning(this.$t(`intro.function.ido.输入`))
      }

      if (this.usdtAmount < 10) {
        return Message.warning(this.$t(`intro.function.ido.最少`))
      }

      if (this.usdtAmount > 300) {
        return Message.warning(this.$t(`intro.function.ido.最多`))
      }

      web3.initContract('IDO').then(() => {
        web3.checkIsRegister(this.userAddress).then((flag) => {
          this.$store.commit('setIsRegister', flag)

          if (flag) {
            web3.initContract('USDT').then(() => {
              web3.approve().then(() => {
                web3.initContract('IDO').then(() => {
                  const amount = this.usdtAmount

                  web3.presale(this.toBigNumber(amount)).then(async (hash) => {
                    const params = {
                      usdt: amount,
                      walletAddress: this.userAddress,
                      hashValue: hash,
                    }

                    const { code } = await this.$apis.savePresaleInfo(params)

                    if (code === 200) {
                      this.usdtAmount = ''
                      this.refresh()
                      Message.success(this.$t('common.交易已上链'))
                    }
                  })
                })
              })
            })
          } else {
            Message.error(`common.请先领取空投`)
          }
        })
      })
    },

    /**
     * 提交注册接口
     */
    submitRegister(hashValue) {
      return new Promise(async (resolve, reject) => {
        try {
          const params = {
            parentWalletAddress: this.inviterAddress,
            walletAddress: this.userAddress,
            hashValue,
          }

          const { code } = await this.$apis.saveRegisterRecord(params)

          if (code === 200) {
            this.refresh()
            resolve(1)
          } else {
            reject(0)
          }
        } catch (err) {
          console.log('注册失败：', err)
          reject(0)
        }
      })
    },

    /**
     * 轮询提现按钮状态
     */
    async getLockStatus() {
      const params = {
        walletAddress: this.userAddress,
        loading: false,
      }

      const { code, data } = await this.$apis.checkUserIsWithdrawing(params)

      if (code === 200) {
        this.isLocked = data

        // 如果锁住，那就轮询查
        if (this.isLocked) {
          setTimeout(this.getLockStatus, 1000 * 30)
        } else {
          this.refresh()
        }
      }
    },

    checkTransferStatus(txId = '') {
      this.checkTimer = setInterval(() => {
        tronWeb.trx.getConfirmedTransaction(txId).then((res) => {
          console.log('查询信息：', res)
          clearInterval(this.checkTimer)

          if (res.ret[0].contractRet === 'SUCCESS') {
            console.log('交易成功')
            setTimeout(this.getBalance, 2000)
          } else {
            console.log('交易失败')
          }
        })
      }, 1000)
    },

    refresh() {
      this.$parent.$parent.checkIsRegister(this.userAddress)
      this.$parent.$parent.getConfigInfo()
      this.$parent.$parent.getUserInfo()
    },

    toBigNumber(amount = 0, limit = 6) {
      if (amount === 0) {
        return '0x0000000000000000000000000000000000000000'
      } else {
        return BigNumber(amount)
          .multipliedBy(10 ** limit)
          .toFixed(0)
      }
    },

    copyLink(link) {
      this.$copyText(link).then(() => {
        this.$message.success(this.$t(`common.复制成功`))
      })
    },
  },

  watch: {
    '$store.state.userAddress': {
      handler() {
        this.userAddress = this.$store.state.userAddress
        this.inviteLink = `${location.origin}/?inviterAddress=${this.userAddress}`
      },
      immediate: true,
    },
  },

  components: {
    baseFunction,
    CountDown,
  },
}
</script>

<style lang="scss" scoped>
#function {
}
</style>
